global class CustomerRightsApplicationBatch implements Database.Batchable<CustomerRightsDetails__c> {
    

    public String soId ; 
    public CustomerRightsApplication__c cra ;
    global CustomerRightsApplicationBatch (){}
    global CustomerRightsApplicationBatch(String soId ) {

       // this.query = 'select Account__c,Account__r.IFuserule__c,Account__r.OwnerId from CustomerRightsDetails__c where CustomerRightsApplication__c =\''+soId +'\' and IsTrans__c != true  limit 1  ';
        this.soId = soId ; 
        this.cra = [select User__c, CustomerRightsType__c from CustomerRightsApplication__c where Id =:this.soId ];

        //[select Account__c,Account__r.IFuserule__c,Account__r.OwnerId from CustomerRightsDetails__c where CustomerRightsApplication__c =:this.soId ]


    }
    global Iterable<CustomerRightsDetails__c> start(Database.batchableContext info){
        
        //if(this.cra == null )return [select Account__c,Account__r.IFuserule__c,Account__r.OwnerId from CustomerRightsDetails__c
        //where CustomerRightsApplication__r.Status__c ='审批成功' and CustomerRightsApplication__r.CustomerRightsType__c ='客户责任人转移'  and IsTrans__c != true  ];
        
        return [select OldOwner__c, Account__c,Account__r.IFuserule__c,Account__r.OwnerId,CustomerRightsApplication__r.OwnerId from CustomerRightsDetails__c
        where CustomerRightsApplication__c=:this.soId and CustomerRightsApplication__r.CustomerRightsType__c ='客户责任人转移'  and IsTrans__c != true  ];

    }

    /*global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }*/

    global void execute(Database.BatchableContext BC, list<CustomerRightsDetails__c> scope) {
        
        SavePoint sp = Database.setSavepoint();

        try {

            Map<Id,Boolean> accMap  = new Map<Id,Boolean >();
            Set<Id> oldOwnerSet   = new Set<Id >();
            Set<Id>accset = new Set<Id>();

            User u = [select Id ,FXProductLine__c from User where Id =:cra.User__c];
          
            for (CustomerRightsDetails__c crd  :scope ) {
                    accMap.put(crd.Account__c,crd.Account__r.IFuserule__c);
                   
                    oldOwnerSet.add(crd.CustomerRightsApplication__r.OwnerId );
                    if(cra.User__c != crd.Account__r.OwnerId )accset.add(crd.Account__c);
                    crd.IsTrans__c = true; 
            }


            System.debug(accMap);
            System.debug(oldOwnerSet);
            if(cra.CustomerRightsType__c == '客户责任人转移'){
                accset.clear();
                // List<Account> accList = new List<Account>();
                // for (Id accid  :accMap.keySet()) {
                //     accList.add(new Account(Id =accid  , OwnerId=cra.User__c,IFuserule__c = !accMap.get(accid)));
                // }
                // if(accList.size()> 0) update accList ;
                // accList.clear();

                 //将nc客户信用的所有人也修改
                List<AccountCredit__c> acList = [select Id from AccountCredit__c where Account__c in: accMap.keySet() and OwnerId in: oldOwnerSet];
                for ( AccountCredit__c ac: acList ) {
                    ac.OwnerId = cra.User__c;
                }
                if(acList.size() > 0)update acList ;
                acList.clear(); 

                

                // 同时把活动的所有人也改了
                List<Event> eList = [select Id  from Event where Account__c in :accMap.keySet() and OwnerId in : oldOwnerSet and Status__c != '完成' ];
                for (Event e : eList) {
                    e.OwnerId = cra.User__c ;
                   
                }

                if(eList.size() > 0 ) update eList;
                eList.clear();


                List<Task> tList = [select Id,OwnerId   from Task where whatId in: accMap.keySet()  and OwnerId in:oldOwnerSet and Status != 'Completed' and ActivityDate >=:System.today().addMonths(-1) ];
              
                for (Task ta :tList ) {
                    ta.OwnerId = cra.User__c;
                }
                if(tList.size() > 0 ) update tList;
                tList.clear();


                //将业务机会的所有人也修改
                List<Opportunity> oList = [select Id from Opportunity where AccountId in :accMap.keySet() and OwnerId in :oldOwnerSet and Is_Stop__c != true and StageName not in ('合同签订','合作确认','失败')  ];
                
                Map<Id,OpportunityShare> oppMap = new Map<Id,OpportunityShare>();
                for(Opportunity o : oList){
                    //o.OwnerId = cra.User__c ;

                    OpportunityShare oshare  = new OpportunityShare();
                    
                    oshare.OpportunityAccessLevel= 'Edit';
                    oshare.UserOrGroupId = cra.User__c;
                    oshare.OpportunityId = o.Id;
                   
                    oppMap.put(o.Id, oshare);

                } 
                for (OpportunityShare os  : [select Id ,OpportunityId from OpportunityShare where  OpportunityId in:oppMap.keySet() and  UserOrGroupId=:cra.User__c ]) {
                    oppMap.remove(os.OpportunityId);
                }
                if(!oppMap.isEmpty()) insert  oppMap.values();
                oppMap.clear();
                // if(oList.size() > 0) update oList;
                // oList.clear();

                //将合同的所有人也修改
                Map<Id,Contract__Share> conMap = new Map<Id,Contract__Share>();
                List<Contract__c> cList = [select Id  from Contract__c where Account__c  in :accMap.keySet()  ];
                for(Contract__c c : cList){
                   // c.OwnerId = cra.User__c ;
                    Contract__Share cshare = new Contract__Share();
                    cshare.AccessLevel = 'Edit';
                    cshare.UserOrGroupId = cra.User__c;
                    cshare.ParentId = c.Id;
                    conMap.put(c.Id, cshare);
                }

                for (Contract__Share os  : [select Id ,ParentId from Contract__Share where  ParentId in:conMap.keySet() and  UserOrGroupId=:cra.User__c ]) {
                    conMap.remove(os.ParentId);
                }

                if(!conMap.isEmpty()) insert  conMap.values();
                conMap.clear();



                Map<Id,InstallationApply__Share> inMap = new Map<Id,InstallationApply__Share>();

                List<InstallationApply__c> inList = [select Id from InstallationApply__c where Hospital__c in: accMap.keySet() and OwnerId in: oldOwnerSet and EndWorkOrderTimen__c = null  ];
                for ( InstallationApply__c ac: inList ) {
                    //ac.OwnerId = cra.User__c ;
                    InstallationApply__Share cshare = new InstallationApply__Share();
                    cshare.AccessLevel = 'Edit';
                    cshare.UserOrGroupId = cra.User__c;
                    cshare.ParentId = ac.Id;
                    inMap.put(ac.Id, cshare);

                }
                 for (InstallationApply__Share os  : [select Id ,ParentId from InstallationApply__Share where  ParentId in:inMap.keySet() and  UserOrGroupId=:cra.User__c ]) {
                    inMap.remove(os.ParentId);
                }

                if(!inMap.isEmpty()) insert  inMap.values();
                inMap.clear();

                Map<Id,InstrumentDeliveryApplication__Share> indMap = new Map<Id,InstrumentDeliveryApplication__Share>();

                //发货申请
                List<InstrumentDeliveryApplication__c> indList = [select Id from InstrumentDeliveryApplication__c where OwnerId in:oldOwnerSet and NC__c != true ];
                for ( InstrumentDeliveryApplication__c ac: indList ) {
                    //ac.OwnerId = cra.User__c ;
                    InstrumentDeliveryApplication__Share cshare = new InstrumentDeliveryApplication__Share();
                    cshare.AccessLevel = 'Edit';
                    cshare.UserOrGroupId = cra.User__c;
                    cshare.ParentId = ac.Id;
                    indMap.put(ac.Id, cshare);
                }
                 for (InstrumentDeliveryApplication__Share os  : [select Id ,ParentId from InstrumentDeliveryApplication__Share where  ParentId in:indMap.keySet() and  UserOrGroupId=:cra.User__c ]) {
                    indMap.remove(os.ParentId);
                }

                if(!indMap.isEmpty()) insert  indMap.values();
                indMap.clear();
            }
            update scope;
            if(System.Test.isRunningTest())throw new DmlException('test');
            
        }
        catch (Exception e) {
            Database.rollback(sp);
            List<Task> tList = new List<Task>();
            for(User u : [select Id from User where Name in:Label.AccountRightErrorInfoPersons.split(',') ]){
                Task t = new Task();
                t.OwnerId  =u.Id ;
                t.Subject = '客户权限转移失败';
                t.Description = '客户权限转移失败:'+e.getMessage()+e.getStackTraceString();
                t.WhatId  = scope[0].Id ;
                t.ActivityDate = System.today();
                tList.add(t);
            }
            insert tList ;
             
        }
        
         
    }


    global void finish(Database.BatchableContext BC) {

    }
}